package com.zlx.exchange.conversation.controller;

import cn.hutool.jwt.JWTUtil;
import com.zlx.exchange.conversation.dao.MessageDao;
import com.zlx.exchange.conversation.service.ConversationService;
import com.zlx.exchange.domain.entity.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;

@RestController
@CrossOrigin
@ServerEndpoint("/chat/{token}")
public class ConversationController {

    private Session session;

    private static ConversationService conversationService;

    @Autowired
    public void setChatService(ConversationService conversationService) {
        ConversationController.conversationService = conversationService;
    }
    @OnOpen
    public void open(Session session, @PathParam("token") String token) {
        this.session = session;
        System.out.println("开启，token" + token
        );
    }

    ;

    @OnClose
    public void close(Session session, CloseReason closeReason) {
        this.session = session;
        System.out.println("关闭");

    }

    @OnError
    public void onError(Session session, Throwable error) {
        this.session = session;
        // 处理发生错误时的逻辑
        System.out.println("WebSocket 发生错误: " + error.getMessage());
    }

    ;

    @OnMessage
    public void sendMessage(String message, @PathParam("token") String token) {
        System.out.println("收到客户端消息:" + message + ",用户" + token);
        conversationService.sendMessage(message, token);
    }

}